package com.user.service.ipl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.user.feign.FeignArticle;
import com.user.mapper.UserFollowMapper;
import com.user.mapper.UserfanMapper;
import com.user.service.UserFollowService;
import com.usian.model.behavior.FollowBehaviorConstants;
import com.usian.model.behavior.FollowBehaviorDto;
import com.usian.model.behavior.LikesBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApAuthor;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserFollowServiceipl extends ServiceImpl<UserFollowMapper, ApUserFollow> implements UserFollowService {

    @Resource
    private UserfanMapper userfanMapper;

    @Resource
    private UserFollowMapper userFollowMapper;

    @Resource
    KafkaTemplate kafkatemplat;

    @Resource
    FeignArticle feignArticle;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
//        内容判断
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        根据传过来的主键id去ApAuthor（作者表）查询
        Integer followid=null;
        ApAuthor apAuthor = feignArticle.findById(dto.getAuthorId());
//        判断是否有这个作者   有的话 给integer值赋值为该作者的主键id
        if (apAuthor!=null){
            followid=apAuthor.getId();
        }
//获取线程池中的登录用户
        ApUser user = AppThreadLocalUtils.getUser();
//        ApUser user=new ApUser();
//        user.setId(4);
//
//        如果没有登录就返回错误信息
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        如果主键id  赋值成功  进行前台的参数判断
//  * 操作方式
//     * 0  关注
//     * 1  取消  看是关注还是取消
        if (followid!=null){
            if (dto.getOperation()==0){
                //                调用各自的方法
                followuser(user,followid,apAuthor);


//                关注成功后 进行 创建点赞列表中信息 创建一个实体类 保存需要的id
//                登录id user  作者主键id  FollowId   ArticleId文章id 关注或者取消
                FollowBehaviorDto dt=new FollowBehaviorDto();
                dt.setArticleId(dto.getArticleId());
                dt.setUserId(user.getId());
                dt.setFollowId(followid);
//                使用kafka进行传递   监听器配置好对应的  密钥
                kafkatemplat.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dt));


            }else {
                quxiaofollowuser(user,followid,apAuthor);
            }
        }

        return null;
    }



    //关注的方法   参数为  登录信息 该作者的信息  以及和作者主键id存储值
    public  ResponseResult followuser(ApUser user,Integer followid,ApAuthor apAuthor){

//      粉丝作者中间表 进行查询 根据作者的主键id 去作者列查询  以及 登录的信息id 去登录列查询
        ApUserFollow apUserFollow = userFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getFollowId, followid).eq(ApUserFollow::getUserId, user.getId()));

//查看是否查询成功   ==null  代表没有关注这个人    进行一个关注的操作
        if (apUserFollow==null){
//            创建粉丝作者中间表对象  进行赋值
            ApUserFollow apUserFollow1=new ApUserFollow();
            apUserFollow1.setIsNotice(true);
            apUserFollow1.setCreatedTime(new Date());
//            粉丝列 和  作者主键id
            apUserFollow1.setFollowId(followid);
            apUserFollow1.setLevel(1);
            apUserFollow1.setFollowName(user.getName());
//            登录列 和 登录id
            apUserFollow1.setUserId(user.getId());
//            今天单表的添加  粉丝作者中间表  表添加这条数据
            userFollowMapper.insert(apUserFollow1);
            ApUserFan apUserFan = userfanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, user.getId()).eq(ApUserFan::getUserId, apUserFollow.getUserId()));
//          中间表添加完成后  再去粉丝表 查询   根据登录id  和作者id

//判断粉丝表是否为空
            if (apUserFan==null){
//                粉丝表再进行一个赋值操作
               ApUserFan apUserFan1=new ApUserFan();
               apUserFan1.setCreatedTime(new Date());
               apUserFan1.setFansId(user.getId().longValue());
               apUserFan1.setFansName(apAuthor.getName());
               apUserFan1.setIsDisplay(true);
               apUserFan1.setLevel(1);
               apUserFan1.setUserId(apAuthor.getUserId());
               apUserFan1.setIsShieldLetter(true);
//               添加
               userfanMapper.insert(apUserFan1);



            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        return ResponseResult.okResult("关注成功");
    }




//    取消关注   大致流程和关注一样 只是赋值字段少 只需要保证这条数据有 并且进行 登录id  和  作者id  进行中间表删除和粉丝表
    public  ResponseResult quxiaofollowuser(ApUser user,Integer followid,ApAuthor apAuthor){
        ApUserFollow apUserFollow = userFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getFollowId, followid).eq(ApUserFollow::getUserId, user.getId()));
        if (apUserFollow==null){
            ApUserFollow apUserFollow1=new ApUserFollow();
            apUserFollow1.setUserId(user.getId());
            userFollowMapper.deleteById(apUserFollow);
//            userFollowMapper.deleteByIdfollow(apUserFollow1.getUserId(),followid);
            ApUserFan apUserFan = userfanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, user.getId()).eq(ApUserFan::getUserId, apUserFollow.getUserId()));
            if (apUserFan==null){
                ApUserFan apUserFan1=new ApUserFan();
                apUserFan1.setFansId(user.getId().longValue());
                apUserFan1.setUserId(apAuthor.getUserId());
                userfanMapper.deleteById(apUserFan);
//                userfanMapper.deleteByIdfan(apUserFan1.getUserId(),apUserFan1.getFansId());

            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        return ResponseResult.okResult("取消关注成功");
    }

}
